<template>
  <div>

    <van-toast id="van-toast" />

    <van-popup :show="show_guopin"  position="bottom" :overlay="true">
      <van-picker show-toolbar title="果品和规格" :columns="columns" @change="onChange"   @cancel="Close_cancelGuoPin" @confirm="Close_confirmGuoPin" />
    </van-popup>



    <van-cell-group>
      <van-cell v-if="isEdit" title="订单号" :value="val_.num" />




      <van-field
        label="果品和规格"
        placeholder="果品和规格"
        @click="Open_GuoPin"
        :value="guopinguige"
        required
        readonly
      />




      <van-cell center title="数量">
        <van-stepper :value="val_.sum" @change="onChangeSum" />
      </van-cell>



      <van-cell v-if="isEdit" title="状态"  class="zhuangtai" >


        <van-radio-group :value="val_state" @change="onChangesState">
          <van-radio name="0">未发货</van-radio>
          <van-radio name="1">已发货</van-radio>
        </van-radio-group>
      </van-cell>



      <van-field
        @change="changeVal_site"
        :value="val_.site"
        label="快递地址"
        type="textarea"
        placeholder="请输入快递地址"
        input-class="textarea"
        autosize
        required
      />

      <van-field
        @change="changeVal_express"
        :value="val_.express"
        label="快递单号"
        type="text"
        placeholder="请输入快递单号"
        autosize
        required
      />



      <div class="btnm" v-if="isEdit">
        <van-button type="info" @click="goform(0)" block>提交修改</van-button>
      </div>
      <div class="btnm" v-if="!isEdit">
        <van-button type="info" @click="goform(1)" block>提交新订单</van-button>
      </div>
      <!--<div class="btnm" v-if="!isEdit">-->
      <!--<van-button plain type="info" @click="addguo" block>提交并拷贝</van-button>-->
      <!--</div>-->
    </van-cell-group>
    <van-dialog id="van-dialog" />

  </div>
</template>

<script>
  import Dialog from '../../../static/vant/dialog/dialog';
  import Toast from  '../../../static/vant/toast/toast';
  import * as dayjs from 'dayjs'
  import 'dayjs/locale/zh-cn' // import locale

  import {orderAdd,orderEdit,orderiInfo,categoryList} from '../../api/basisMG'


  export default {
    data () {
      return{
        val_state:'',
        pickerData:[],
        guopinguige:"",
        columns:[],
        username:"",
        show_guopin:false,
        isEdit:false,
        val_:{
          express:"",
          addtime: "",
          deltime: "",
          guige: "",
          guopin: "",
          num: "",
          site: "",
          state: "",
          sum: 1,
          username: "",
          _id: "",
          _openid: "",
        }
      }
    },

    onShow() {
      this.guopinguige = ""
    },
    //
    // beforeMount(){
    //   },


    mounted() {

      //加载果品目录
      categoryList().then(res => {

          if(res.data.length){
            this.columns = [{
              values: ["请选择果品"],
              className: 'column1'
            },{
              values: ["请选择规格"],
              className: 'column2',
              defaultIndex: 0
            }]


            this.pickerData = res.data;
            console.log(this.pickerData)

            //给一级目录数据
            for(let i = 0;i<res.data.length;i++){
              this.columns[0].values.push({text:res.data[i].text,id:res.data[i].id})
            }


          }
        }
      )



      //可选目录
      //this.columns_guopin = this.globalData.guopinArray
      //this.columns_guige = this.globalData.guigeArray
      this.username = wx.getStorageSync('loginInfo').username

      //判断是新增还是修改
      if(this.$root.$mp.query.id){
        this.isEdit =true
        wx.setNavigationBarTitle({
          title: '修改订单'
        })
        this.loadOrderData()
      }else{
        this.isEdit = false
        //清空原来的表单
        this.val_={
          express:'',
          addtime: "",
          deltime: "",
          guige: "",
          guopin: "",
          num: "",
          site: "",
          state: "",
          sum: 1,
          _id:""
          //username: "",
          //_id: "",
          //_openid: "",
        }
        this.columns_guopin_text = ""
        this.columns_guige_text = ""
      }
    },
    methods: {


      onChangesState(event){

        this.val_.state = event.mp.detail
        this.val_state = event.mp.detail
        console.log(333)
        console.log(this.val_.state)
        // this.aaa = event.mp.detail
      },

      onChange(picker,value,index){
        //if(index == 0){
        var arr = []
        for(var i in this.pickerData){
          if(picker.mp.detail.value[0].id == this.pickerData[i].id){

            var obj = {
              text:"请选择规格"
            }
            arr.push(obj)

            for(var x in this.pickerData[i].children){
              var obj = {
                text:this.pickerData[i].children[x].text,
                id:this.pickerData[i].children[x].id
              }
              if(this.pickerData[i].children[x].show){
                arr.push(obj)
              }
            }


          }
        }
        this.columns[1].values =arr

        try {
          this.guopinguige = (picker.mp.detail.value[0].text||'请选择果品')+" "+ (picker.mp.detail.value[1].text||'请选择规格')

        } catch(err){
          this.guopinguige = picker.mp.detail.value[0].text||'请选择果品'
        }


      },


      loadOrderData(){
        Toast.loading({
          message: '加载中...'
        });

        orderiInfo({"_id":this.$root.$mp.query.id}).then(res => {



          if(res.data){
            let data = res.data
            this.val_ = data
            this.val_state = this.val_.state+""
            console.log( this.val_ )

            console.log( this.val_state )
            // if(this.val_.state!=null){
            //   this.val_.state = this.val_.state+""
            // }else{
            //   this.val_.state = "2"
            // }



            let guopintextar = this.pickerData.filter((obj,index)=>{
              if(obj.id ==this.val_.guopin){
                return obj
              }
            })

            let guopintextar_text = guopintextar[0].text
            let guigetextar_text = guopintextar[0].children.filter((obj,index)=>{
              if(obj.id ==this.val_.guige){
                return obj
              }
            })[0].text


            this.guopinguige = guopintextar_text + guigetextar_text
            //this.val_.guopin+this.val_.guige
          }
        })
      },

      Open_GuoPin(){
        this.show_guopin = true
      },

      Close_confirmGuoPin(picker) {
        try {
          this.val_.guopin = picker.mp.detail.value[0].id
          this.val_.guige = picker.mp.detail.value[1].id
        }catch (e) {
          this.val_.guige = ""
          this.val_.guopin = ""
        }

        this.show_guopin = false
      },

      Close_cancelGuoPin(){
        this.guopinguige = ""
        this.val_.guopin = ""
        this.val_.guige = ""
        this.show_guopin = false
      },


      onChangeSum(data){
        this.val_.sum = data.mp.detail
      },

      changeVal_express(data){
        console.log(data)
        this.val_.express = data.mp.detail
      },

      changeVal_site(data){
        this.val_.site = data.mp.detail
      },

      goform(isNew){


        let t = this
        console.log(t.val_)

        if(!t.val_.guopin){
          Dialog.alert({
            message: '没有选择果品，请选择果品'
          })
          return false
        }

        if(!t.val_.guige){
          Dialog.alert({
            message: '没有选择规格，请选择规格'
          })
          return false
        }

        if(!t.val_.site){
          Dialog.alert({
            message: '地址未填写'
          })
          return false
        }

        if(t.val_.site.indexOf(",") != -1){
          t.val_.site = t.val_.site.replace(/,/g,"，")
        }

        if(t.val_.site.indexOf("\n") != -1){
          t.val_.site = t.val_.site.replace(/\n/g," ")
        }



        let neworder = {
          guopin:t.val_.guopin,
          sum:t.val_.sum,
          guige:t.val_.guige,
          site:t.val_.site,
          state:t.val_.state*1,
          express:t.val_.express
        }
        if(isNew){
          neworder.username = t.username
          orderAdd(neworder).then(res => {
            Dialog.alert({
              message: '添加订单成功！'
            }).then(() => {
              wx.redirectTo({
                url: "/pages/order/main"
              })
            });
          })
        }else{
          var timestamp = Date.parse(new Date());
          neworder.edittime = timestamp/1000
          neworder._id = this.val_._id


          console.log(neworder)
          orderEdit(neworder).then(res => {
            Dialog.alert({
              message: '修改订单成功！'
            }).then(() => {
              wx.redirectTo({
                url: "/pages/manageOrder/main"
              })
            });
          })
        }





      },





    },

    created () {
      // let app = getApp()
    }
  }
</script>

<style >
  .btnm{padding: 32rpx}

  .textarea{
    min-height: 222rpx!important;
    padding-top: 20rpx!important;
  }

  page {
    background-color: #fff;
  }



  .tr {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .th, .td {
    padding: 10px;
    border-bottom: 1px solid #dadada;
    border-right: 1px solid #dadada;
    text-align: center;
    width: 100%;
  }

  .th {
    font-weight: 400;
    background-color: #dadada;
  }

  ._van-radio{float: left; margin-right: 22rpx}

</style>
